const isDev = import.meta.env.DEV;

const API_BASE = isDev ? "/" : "https://wk.kuai-d.com";

function buildUrl(path, query = {}) {
  let requestUrl;
  
  if (API_BASE.startsWith("http")) {
    // 生产环境
    const url = new URL(path, API_BASE);
    Object.entries(query).forEach(([key, value]) => {
      if (value !== undefined && value !== null)
        url.searchParams.set(key, String(value));
    });
    requestUrl = url.toString();
  } else {
    // 开发环境
    const url = new URL(path, window.location.origin);
    Object.entries(query).forEach(([key, value]) => {
      if (value !== undefined && value !== null)
        url.searchParams.set(key, String(value));
    });
    requestUrl = url.pathname + url.search;
  }
  
  return { requestUrl };
}

export async function fetchDeviceInfo(deviceName) {
  const { requestUrl } = buildUrl("/api/app/device/device-tabel", { deviceName });
  
  const res = await fetch(requestUrl, {
    method: "GET",
    headers: { Accept: "application/json" },
  });
  if (!res.ok) throw new Error("DEVICE_INFO_HTTP_" + res.status);
  const data = await res.json().catch(() => ({}));
  return data;
}

export async function setDeviceStatus({ mac, command, temperature }) {
  const { requestUrl } = buildUrl("/api/app/device/set-device-status");
  
  const res = await fetch(requestUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json", Accept: "application/json" },
    body: JSON.stringify({ mac, command, temperature }),
  });
  if (!res.ok) throw new Error("SET_STATUS_HTTP_" + res.status);
  const data = await res.json().catch(() => ({}));
  return data;
}

